import { queryStateByCode } from '@/api/dict';

export const DictMap = new Map();

export type TDict = Record<string, string>;

export const getDict = (type: string): Promise<TDict> => {
  if (DictMap.has(type)) {
    return Promise.resolve(DictMap.get(type));
  }

  return queryStateByCode(type).then((res) => {
    const dictObj: Record<string, string> = {};
    res.forEach((element: any) => {
      dictObj[element.stateValue] = element.stateLabel;
    });

    DictMap.set(type, dictObj);

    return dictObj;
  });
};

export const getDictLabel = (type: string, value: string): Promise<string> => {
  return getDict(type).then((dict) => {
    return dict[value];
  });
};
